using System;

namespace LiJ.Common.Core.Utils
{
	/// <summary>
	///   Ioc简单实例容器实现
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public static class InsContainer<T>
	{
		private static Func<T> _instanceCreater;

		private static T _instance;

		/// <summary>
		///  具体实例 
		/// 根据设置时参数会返回具体单例还是新的实例
		/// </summary>
		public static T Instance
		{
			get
			{
				if (_instanceCreater == null)
				{
					throw new Exception(" 并没有设置" + typeof(T).Name + "对应的映射类型！ ");
				}
				return _instanceCreater();
			}
		}

		/// <summary>
		///  设置具体类型映射关系
		/// </summary>
		/// <typeparam name="TInstance"></typeparam>
		/// <param name="isSingle">是否是单例模式</param>
		public static void Set<TInstance>(bool isSingle = true) where TInstance : T, new()
		{
			if (_instanceCreater == null)
			{
                _instanceCreater = delegate
				{
					if (isSingle)
					{
						return (T)(object)new TInstance();
					}
					if (_instance != null)
					{
						return _instance;
					}
					return _instance = (T)(object)new TInstance();
				};
			}
		}
	}
}
